﻿using ImageRenderControl;
using System.Collections.ObjectModel;
using System.Drawing;
using System.Windows;
using System.Windows.Forms;
using VisionDesigner;
using VM.Common.Enums;
using VM.Dialogs.Views;

namespace VM.Controls
{
    /// <summary>
    /// DisplayControl.xaml 的交互逻辑
    /// </summary>
    public partial class DisplayControl : System.Windows.Controls.UserControl
    {

        public List<MVD_POINT_F> PointSet = new List<MVD_POINT_F>();
        public CMvdShape boolcircle = null;
        #region 依赖属性
        // 输入图像
        public static readonly DependencyProperty ImageProperty =
            DependencyProperty.Register(
                "Image", typeof(CMvdImage), typeof(DisplayControl),
                new PropertyMetadata(null, OnCMvdImagePropertyChanged));

        private CMvdImage _image;
        public CMvdImage Image
        {
            set
            {
                _ImageLoaded = false;
                if (_image != value)
                {
                    _image?.Dispose();
                    _image = value;
                    SetValue(ImageProperty, value);
                }
                else
                {
                    CMvdImage oldValue = _image;
                    _image = value;
                    SetValue(ImageProperty, value);
                    // 手动触发属性改变通知
                    OnCMvdImagePropertyChanged(this, new DependencyPropertyChangedEventArgs(ImageProperty, oldValue, _image));
                }
            }
            get
            {
                if (!Dispatcher.CheckAccess()) // 如果不在 UI 线程，切换到 UI 线程获取值
                {
                    return (CMvdImage)Dispatcher.Invoke(() => GetValue(ImageProperty));
                }
                return (CMvdImage)GetValue(ImageProperty);
            }
        }

        private static void OnCMvdImagePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is not DisplayControl control)
                return;

            if (e.NewValue is not CMvdImage image)
                image = new CMvdImage();
            if (e.NewValue == DependencyProperty.UnsetValue || e.NewValue == null)
                return;
            try
            {
                if (!image.IsEmpty)
                {
                    control.MVDRender.LoadImageFromObject(image);
                    control._ImageLoaded = true;
                }
                else
                {
                    ClearRenderContent(control);
                }
            }
            catch
            {
                // 如果加载或清除操作失败，标记为未加载
                control._ImageLoaded = false;
            }
            finally
            {
                // 始终调用显示刷新方法
                control.MVDRender.Display();
            }
        }

        /// <summary>
        /// 清理 MVD 渲染器的内容
        /// </summary>
        /// <param name="control">DisplayControl 控件实例</param>
        private static void ClearRenderContent(DisplayControl control)
        {
            control._ImageLoaded = false;
            control.MVDRender.ClearImages();
            control.MVDRender.ClearShapes();
            control.AddedShapes?.Clear();
            control._addedShapes?.Clear();
        }

        // 已经绘制添加的图形
        public static readonly DependencyProperty AddedShapesProperty =
            DependencyProperty.Register(
                "AddedShapes",
                typeof(ObservableCollection<CMvdShape>),
                typeof(DisplayControl),
                new PropertyMetadata(new ObservableCollection<CMvdShape>(), OnAddedShapesPropertyChanged));

        // 为 AddedShapes 设置公开的属性访问器，直接使用绑定
        public ObservableCollection<CMvdShape> AddedShapes
        {
            get => (ObservableCollection<CMvdShape>)GetValue(AddedShapesProperty);
            set => SetValue(AddedShapesProperty, value);
        }

        private static void OnAddedShapesPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            DisplayControl control = (DisplayControl)d;

            var newShapes = e.NewValue as ObservableCollection<CMvdShape>;
            var oldShapes = e.OldValue as ObservableCollection<CMvdShape>;

            if (oldShapes != null)
            {
                // 确保在 UI 线程上更新
                if (control.Dispatcher.CheckAccess())
                {
                    control.RemoveShapes(oldShapes);
                }
                else
                {
                    control.Dispatcher.Invoke(() => control.RemoveShapes(oldShapes));
                }
            }

            if (newShapes != null)
            {
                // 确保在 UI 线程上更新
                if (control.Dispatcher.CheckAccess())
                {
                    control.UpdateShapes(newShapes);
                }
                else
                {
                    control.Dispatcher.Invoke(() => control.UpdateShapes(newShapes));
                }
            }
        }

        // 定义 IsClearContent 依赖属性
        public static readonly DependencyProperty IsClearContentProperty =
            DependencyProperty.Register(
                "IsClearContent",
                typeof(bool),
                typeof(DisplayControl),
                new PropertyMetadata(false, OnIsClearContentPropertyChanged));

        // IsClearContent 属性的公开访问器
        public bool IsClearContent
        {
            get => (bool)GetValue(IsClearContentProperty);
            set => SetValue(IsClearContentProperty, value);
        }

        // 属性变更回调
        private static void OnIsClearContentPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is not DisplayControl control)
                return;

            // 如果新值为 true，清空内容并将值重置为 false
            if ((bool)e.NewValue)
            {
                control.ClearDisplayContent();
                control.IsClearContent = false;
            }
        }

        // 清理显示内容的方法
        private void ClearDisplayContent()
        {
            ClearRenderContent(this); // 调用已有的清理方法
            MVDRender.Display(); // 刷新显示
        }

        #endregion
        #region 属性
        // 海康显示控件
        [NonSerialized]
        private VisionDisplayControl _displayControl;
        public MVDRenderActivex MVDRender
        {
            get
            {
                try
                {
                    _displayControl ??= new VisionDisplayControl();
                    return _displayControl.MVDRender;
                }
                catch (Exception ex)
                {
                    MessageView.Ins.MessageBoxShow("没有正确安装视觉环境！", eMsgType.Error);
                    return null;
                }
            }
        }

        public LayeredOverlayForm OverlayFrom
        {
            get
            {
                try
                {
                    _displayControl ??= new VisionDisplayControl();
                    return _displayControl.overlayForm;
                }
                catch (Exception ex)
                {
                    return null;
                }
            }
        }

        public System.Windows.Forms.Label ContentLabel
        {
            get
            {
                try
                {
                    _displayControl ??= new VisionDisplayControl();
                    return _displayControl.ContentLabel;
                }
                catch (Exception ex)
                {
                    MessageView.Ins.MessageBoxShow("没有正确安装视觉环境！", eMsgType.Error);
                    return null;
                }
            }
        }

        // 图片正常加载
        private volatile bool _ImageLoaded = false;
        public CMvdLineSegmentF CrossLevel;
        public CMvdLineSegmentF CrossVertical;
        public CMvdLineSegmentF CrossLevel1;
        public CMvdLineSegmentF CrossVertical1;
        private CMvdShape cMvdShape;
        private bool _drawStart = false;
        private bool _suppressContextMenu = false; // 控制是否禁用菜单显示
        private CMvdShape selectShape = null;
        private static bool JoggingFlag = false;
        private static bool DistanceFlag = false;
        private static bool CrossFlag = false;
        private static bool Circle = false;
        private static bool CenterFlag = false;
        public ObservableCollection<CMvdShape> _addedShapes = new ObservableCollection<CMvdShape>();  // 已经绘制添加的图形
        public CMvdTextF TextContent = new CMvdTextF(0, 0, " ");

        // 绘制ROI
        public CMvdShape? m_ROI;
        private ToolStripMenuItem RoiMenu = new ToolStripMenuItem("绘制模板");

        //private ToolStripMenuItem subItem1 = new ToolStripMenuItem("全图");
        private ToolStripMenuItem subItem2 = new ToolStripMenuItem("矩形");
        private ToolStripMenuItem subItem3 = new ToolStripMenuItem("圆形");

        // 事件
        public event EventHandler<PointDataEventArgs>? PointDataSent;
        public event EventHandler<TrajectoryPointsEventArgs>? TrajectoryPointsGenerated;
        public event EventHandler<ROIShapeEventArgs>? ROIShapeCreated;

        // 绘制轨迹
        // 当前绘图状态
        private DrawingState currentDrawingState = DrawingState.None;
        // 绘图相关的临时变量
        private System.Drawing.Point? firstPoint = null;
        private System.Drawing.Point? secondPoint = null; // 用于圆弧的第二个点
        private List<System.Drawing.Point> curvePoints = new List<System.Drawing.Point>(); // 用于存储曲线的控制点

        // 添加用于临时预览的变量
        private ImageRenderControl.Shape previewShape = null; // 用于预览的临时形状
        private System.Windows.Forms.Timer previewUpdateTimer; // 用于平滑更新预览的定时器

        #endregion
        /// <summary>
        /// 构造函数
        /// </summary>
        public DisplayControl()
        {
            InitializeComponent();

            // 初始化预览更新定时器
            previewUpdateTimer = new System.Windows.Forms.Timer();
            previewUpdateTimer.Interval = 50; // 50毫秒更新一次，可调整
            previewUpdateTimer.Tick += PreviewUpdateTimer_Tick;

            if (MVDRender != null)
            {
                winFormHost.Child = _displayControl;
                ////设置渲染控件背景色
                //MVDRender.BackColor = Color.FromArgb(0, 0, 0, 0);
                //设置切换同分辨率图像保留图形
                MVDRender.EnableRetainShape = true;
                //设置菜单语言为中文
                MVDRender.MenuLanguage = MVDRenderMenuLangType.Chinese;
                //设置交互模式，自定义交互
                MVDRender.InteractType = MVDRenderInteractType.StandardAndCustom;
                MVDRender.SetConfiguration((uint)MVD_RENDER_PARAM_KEY.MvdRenderSmoothingMode, (int)MVD_RENDER_SMOOTHING_MODE.MvdSmoothingModeHighQuality);

                MVDRender.ContextMenuStrip = new System.Windows.Forms.ContextMenuStrip();
                MVDRender.ContextMenuStrip.Items.Add("开始点动");
                MVDRender.ContextMenuStrip.Items.Add("绘制轨迹");
                MVDRender.ContextMenuStrip.Items.Add("计算距离");
                MVDRender.ContextMenuStrip.Items.Add("选中删除");
                MVDRender.ContextMenuStrip.Items.Add("指针");
                MVDRender.ContextMenuStrip.Items.Add("平移");
                MVDRender.ContextMenuStrip.Items.Add("十字");
                MVDRender.ContextMenuStrip.Items.Add("中心");
                MVDRender.ContextMenuStrip.Items.Add("保存原图");
                MVDRender.ContextMenuStrip.Items.Add("保存结果图");
                MVDRender.ContextMenuStrip.Items.Add("旋转");
                MVDRender.ContextMenuStrip.Items.Add("椭圆");
                //RoiMenu.DropDownItems.Add(subItem1);
                RoiMenu.DropDownItems.Add(subItem2);
                RoiMenu.DropDownItems.Add(subItem3);
                MVDRender.ContextMenuStrip.Items.Add(RoiMenu);

                MVDRender.ContextMenuStrip.Opening += ContextMenuStrip_Opening;
                //设置同分辨率保留图形
                MVDRender.SetConfiguration(itou(MVD_RENDER_PARAM_KEY.MvdRenderRetainShape), utoi(true));
                MVDRender.ContextMenuStrip.ItemClicked += ContextMenuStrip_ItemClicked;
                MVDRender.Display();

                MVDRender.MVDMouseEvent += MVDRender_MVDMouseEvent;
                MVDRender.MVDShapeChangedEvent += MVDRender_MVDShapeChangedEvent;
                ////全图事件
                //subItem1.Click += (sender, e) =>
                //{

                //};
                //矩形事件
                subItem2.Click += (sender, e) =>
                {
                    MVDRender.SetMenuState(System.Convert.ToUInt32(MVD_MENU_ID.MvdRectangle), System.Convert.ToUInt32(MVD_MENU_CMD.MvdMenuSelect), null);
                };
                //圆形事件
                subItem3.Click += (sender, e) =>
                {
                    MVDRender.SetMenuState(System.Convert.ToUInt32(MVD_MENU_ID.MvdCircle), System.Convert.ToUInt32(MVD_MENU_CMD.MvdMenuSelect), null);
                };
            }
        }

        private void ContextMenuStrip_Opening(object? sender, System.ComponentModel.CancelEventArgs e)
        {
            // 动态判断是否需要显示菜单
            if (_suppressContextMenu)
            {
                _suppressContextMenu = false;
                e.Cancel = true; // 阻止菜单显示
            }
        }

        private void ContextMenuStrip_ItemClicked(object? sender, System.Windows.Forms.ToolStripItemClickedEventArgs e)
        {
            if (e.ClickedItem.Text == "绘制轨迹")
            {
                if (_drawStart || JoggingFlag)
                {
                    return;
                }
                MVDRender.SetMenuState(System.Convert.ToUInt32(MVD_MENU_ID.MvdPolylineSegment), System.Convert.ToUInt32(MVD_MENU_CMD.MvdMenuSelect), null);
                // 禁用右键菜单的再次显示
                _drawStart = true;
            }

            else if (e.ClickedItem.Text == "选中删除")
            {
                RemoveShape(selectShape);
                selectShape = null;
            }
            else if (e.ClickedItem.Text == "开始点动")
            {
                JoggingFlag = true;
                MVDRender.InteractType = MVDRenderInteractType.Custom;
                e.ClickedItem.Text = "停止点动";
            }
            else if (e.ClickedItem.Text == "停止点动")
            {
                JoggingFlag = false;
                e.ClickedItem.Text = "开始点动";
            }
            else if (e.ClickedItem.Text == "指针")
            {
                _drawStart = false;
                MVDRender.SetMenuState(System.Convert.ToUInt32(MVD_MENU_ID.MvdPointer), System.Convert.ToUInt32(MVD_MENU_CMD.MvdMenuSelect), null);


                var rect = new RectangleShape(100, 100, 200, 300);
                var arc = new ArcShape(
                    new PointF(100, 100),
                    new PointF(150, 50),
                    new PointF(200, 100)
                );
                var line = new LineShape(new PointF(200, 200), new PointF(300, 250));

                // 创建一个 List<PointF> 实例
                List<PointF> points = new List<PointF>();

                // 添加一些 PointF 实例到列表中
                points.Add(new PointF(100.5f, 200.3f));
                points.Add(new PointF(300.1f, 400.2f));
                points.Add(new PointF(400.1f, 200.2f));
                points.Add(new PointF(700.1f, 600.2f));
                points.Add(new PointF(200.1f, 500.2f));

                var Interpolated = new InterpolatedCurveShape(points);

                _displayControl.overlayForm.AddShape(rect);
                _displayControl.overlayForm.AddShape(arc);
                _displayControl.overlayForm.AddShape(line);
                _displayControl.overlayForm.AddShape(Interpolated);

            }
            else if (e.ClickedItem.Text == "平移")
            {
                _drawStart = false;
                MVDRender.SetMenuState(System.Convert.ToUInt32(MVD_MENU_ID.MvdPan), System.Convert.ToUInt32(MVD_MENU_CMD.MvdMenuSelect), null);
            }
            else if (e.ClickedItem.Text == "计算距离")
            {
                _drawStart = false;
                MVDRender.SetMenuState(System.Convert.ToUInt32(MVD_MENU_ID.MvdLineSegment), System.Convert.ToUInt32(MVD_MENU_CMD.MvdMenuSelect), null);
            }
            else if (e.ClickedItem.Text == "十字")
            {
                CrossFlag = true;
                e.ClickedItem.Text = "停止十字";

            }
            else if (e.ClickedItem.Text == "停止十字")
            {
                CrossFlag = false;
                if (CrossLevel != null || CrossVertical != null)
                {
                    RemoveShape(cMvdShape);
                    RemoveShape(CrossLevel);
                    RemoveShape(CrossVertical);
                }
                e.ClickedItem.Text = "十字";
            }
            else if (e.ClickedItem.Text == "中心")
            {
                CenterFlag = true;
                e.ClickedItem.Text = "关闭中心";

            }
            else if (e.ClickedItem.Text == "关闭中心")
            {
                CenterFlag = false;
                if (CrossLevel1 != null || CrossVertical1 != null)
                {
                    RemoveShape(CrossLevel1);
                    RemoveShape(CrossVertical1);
                }
                e.ClickedItem.Text = "中心";
            }
            else if (e.ClickedItem.Text == "保存原图")
            {
                _drawStart = false;
                MVDRender.SetMenuState(System.Convert.ToUInt32(MVD_MENU_ID.MvdOriginalImage), System.Convert.ToUInt32(MVD_MENU_CMD.MvdMenuSelect), null);
            }
            else if (e.ClickedItem.Text == "保存结果图")
            {
                _drawStart = false;
                if (_ImageLoaded)
                    MVDRender.SetMenuState(System.Convert.ToUInt32(MVD_MENU_ID.MvdResultImage), System.Convert.ToUInt32(MVD_MENU_CMD.MvdMenuSelect), null);
            }
            else if (e.ClickedItem.Text == "旋转")
            {
                _drawStart = false;
                MVDRender.SetMenuState(System.Convert.ToUInt32(MVD_MENU_ID.MvdRotateRight), System.Convert.ToUInt32(MVD_MENU_CMD.MvdMenuSelect), null);
            }

            MVDRender.Display();
        }

        #region 事件
        /// <summary>
        /// 鼠标事件
        /// </summary>
        /// <param name="enMouseEventType"></param>
        /// <param name="nPointX"></param>
        /// <param name="nPointY"></param>
        /// <param name="nZDelta"></param>
        /// <exception cref="MvdException"></exception>
        private void MVDRender_MVDMouseEvent(MVDMouseEventType enMouseEventType, int nPointX, int nPointY, short nZDelta)
        {

            // 处理绘图状态
            if (currentDrawingState != DrawingState.None)
            {
                // 图像像素坐标
                float imageX = 0.0f, imageY = 0.0f;
                MVDRender.TransformCoordinate(nPointX, nPointY, ref imageX, ref imageY, MVDCoordTransType.Wnd2Img);

                // 转换为 overlayForm 坐标
                int overlayX, overlayY;
                _displayControl.MVDWindowToOverlay(nPointX, nPointY, out overlayX, out overlayY);

                // 处理鼠标移动，显示预览
                if (enMouseEventType == MVDMouseEventType.MouseMove)
                {
                    switch (currentDrawingState)
                    {
                        case DrawingState.DrawingRectangle:
                            if (firstPoint.HasValue)
                                UpdateRectanglePreview((int)imageX, (int)imageY);
                            break;

                        case DrawingState.DrawingLine:
                            if (firstPoint.HasValue)
                                UpdateLinePreview((int)imageX, (int)imageY);
                            break;

                        case DrawingState.DrawingArc:
                            if (firstPoint.HasValue && secondPoint.HasValue)
                                UpdateArcPreview((int)imageX, (int)imageY);
                            break;

                        case DrawingState.DrawingInterpolatedCurve:
                            // 对于曲线，只要有点就持续更新预览
                            if (curvePoints.Count > 0)
                                UpdateCurvePreview((int)imageX, (int)imageY);
                            break;
                    }
                }
                // 处理鼠标左键按下，设置点或完成绘制
                else if (enMouseEventType == MVDMouseEventType.LButtonDown)
                {
                    // 图像边界检查
                    if (_ImageLoaded && (imageX < 0 || imageX >= Image.Width || imageY < 0 || imageY >= Image.Height))
                    {
                        return; // 超出图像边界，不处理
                    }

                    switch (currentDrawingState)
                    {
                        case DrawingState.DrawingRectangle:
                            HandleRectangleDrawing((int)imageX, (int)imageY, overlayX, overlayY);
                            break;

                        case DrawingState.DrawingLine:
                            HandleLineDrawing((int)imageX, (int)imageY, overlayX, overlayY);
                            break;

                        case DrawingState.DrawingArc:
                            HandleArcDrawing((int)imageX, (int)imageY, overlayX, overlayY);
                            break;

                        case DrawingState.DrawingInterpolatedCurve:
                            HandleCurveDrawing((int)imageX, (int)imageY, overlayX, overlayY);
                            break;
                    }
                }
                // 处理鼠标右键按下，取消或结束绘制
                else if (enMouseEventType == MVDMouseEventType.RButtonDown)
                {
                    // 对于曲线绘制，右键完成绘制
                    if (currentDrawingState == DrawingState.DrawingInterpolatedCurve && curvePoints.Count >= 2)
                    {
                        FinalizeCurveDrawing();
                    }
                    // 其他绘图模式，右键取消
                    else
                    {
                        EndDrawing();
                    }
                }

                // 阻止继续处理其他默认事件
                return;
            }


            if (enMouseEventType == MVDMouseEventType.MouseMove)
            {
                float x = 0.0f, y = 0.0f;
                MVDRender.TransformCoordinate(nPointX, nPointY, ref x, ref y, MVDCoordTransType.Wnd2Img);

                if (_ImageLoaded)
                {
                    int nImagePointX = (int)x;
                    int nImagePointY = (int)y;
                    int nWidth = (int)Image.Width;
                    int nHeight = (int)Image.Height;
                    if (nImagePointX < 0 || nImagePointX >= nWidth
                        || nImagePointY < 0 || nImagePointY >= nHeight)
                    {
                        return;
                    }
                    string pixelInfo = string.Empty;
                    List<byte> pixelValue = Image.GetPixel(nImagePointX, nImagePointY);
                    MVD_PIXEL_FORMAT enPixelFormat = Image.PixelFormat;
                    if (MVD_PIXEL_FORMAT.MVD_PIXEL_MONO_08 == enPixelFormat)
                    {
                        pixelInfo = string.Format("X:{0:D4} Y:{1:D4} | R:{2:D3} G:{3:D3} B:{4:D3}", nImagePointX, nImagePointY, pixelValue[0], pixelValue[0], pixelValue[0]);
                    }
                    else if (MVD_PIXEL_FORMAT.MVD_PIXEL_RGB_RGB24_C3 == enPixelFormat)
                    {
                        pixelInfo = string.Format("X:{0:D4} Y:{1:D4} | R:{2:D3} G:{3:D3} B:{4:D3}", nImagePointX, nImagePointY, pixelValue[0], pixelValue[1], pixelValue[2]);
                    }
                    else
                    {
                        throw new MvdException(MVD_MODULE_TYPE.MVD_MODUL_APP, MVD_ERROR_CODE.MVD_E_SUPPORT, "Unsupported pixel format.");
                    }
                    ContentLabel.Text = pixelInfo;
                    ContentLabel.Refresh();
                }
            }

            if (_suppressContextMenu)
            {
                return;
            }

            if (enMouseEventType == MVDMouseEventType.RButtonUp)
            {
                MVDRender.InteractType = MVDRenderInteractType.StandardAndCustom;
            }
            else if (enMouseEventType == MVDMouseEventType.RButtonDown)
            {
                MVDRender.InteractType = MVDRenderInteractType.Custom;
            }
            else if (enMouseEventType == MVDMouseEventType.LButtonDown)
            {
                _displayControl.overlayForm.ClearSelection();
                if (_drawStart)
                {
                    _drawStart = false;
                    _suppressContextMenu = true;
                }

                if (JoggingFlag)
                {
                    float x = 0.0f, y = 0.0f;
                    MVDRender.TransformCoordinate(nPointX, nPointY, ref x, ref y, MVDCoordTransType.Wnd2Img);

                    if (_ImageLoaded)
                    {
                        int nImagePointX = (int)x;
                        int nImagePointY = (int)y;

                        // 检查点位是否在图像范围内
                        if (nImagePointX < 0 || nImagePointX >= Image.Width
                            || nImagePointY < 0 || nImagePointY >= Image.Height)
                        {
                            return;
                        }

                        OnPointDataSent(nImagePointX, nImagePointY);
                    }
                }
                //if (Circle)
                //{
                //    float x = 0.0f, y = 0.0f;
                //    MVDRender.TransformCoordinate(nPointX, nPointY, ref x, ref y, MVDCoordTransType.Wnd2Img);

                //    if (_ImageLoaded)
                //    {
                //        int nImagePointX = (int)x;
                //        int nImagePointY = (int)y;

                //        // 检查点位是否在图像范围内
                //        if (nImagePointX < 0 || nImagePointX >= Image.Width
                //            || nImagePointY < 0 || nImagePointY >= Image.Height)
                //        {
                //            return;
                //        }
                //        MVD_POINT_F pointmp = new MVD_POINT_F();
                //        pointmp.fX = nImagePointX;
                //        pointmp.fY = nImagePointY;
                //        PointSet.Add(pointmp);
                //        if (boolcircle!=null)
                //        {MVDRender.DeleteShape(boolcircle);
                //            boolcircle = null;

                //        }
                //        if (PointSet.Count == 3)
                //        {
                //            // MVD_POINT_F center;
                //            // double radius;
                //            // GetCircleFromThreePoints(PointSet[0], PointSet[1], PointSet[2],out  center, out radius);
                //            //CMvdCircleF cMvdCircleF = new CMvdCircleF(center, (float)radius);
                //            // boolcircle = cMvdCircleF;
                //            // boolcircle.Interaction = true;
                //            // boolcircle.BorderColor = new MVD_COLOR(255, 0, 0, 255);
                //            // boolcircle.BorderWidth = 3;
                //            // AddShape(boolcircle);
                //            // PointSet.Clear();

                //            MVD_POINT_F center;
                //            double radius;
                //            double startAngle;
                //            double endAngle;
                //            double isCounterClockwise;
                //            GetArcParameters(PointSet[0], PointSet[1], PointSet[2], out center, out radius, out startAngle, out endAngle,out isCounterClockwise);
                //            CMvdAnnularSectorF cMvdCircleF = new CMvdAnnularSectorF(center, (float)radius-1, (float)radius, (float)startAngle, (float)isCounterClockwise);
                //            boolcircle = cMvdCircleF;
                //            boolcircle.Interaction = true;
                //            boolcircle.BorderColor = new MVD_COLOR(255, 0, 0, 255);
                //            boolcircle.BorderWidth = 3;
                //            AddShape(boolcircle);
                //            PointSet.Clear();
                //        }
                //    }
                //}
                if (CrossFlag)
                {
                    float x = 0.0f, y = 0.0f;
                    MVDRender.TransformCoordinate(nPointX, nPointY, ref x, ref y, MVDCoordTransType.Wnd2Img);
                    if (_ImageLoaded)
                    {
                        int nImagePointX = (int)x;
                        int nImagePointY = (int)y;

                        // 检查点位是否在图像范围内
                        if (nImagePointX < 0 || nImagePointX >= Image.Width
                            || nImagePointY < 0 || nImagePointY >= Image.Height)
                        {
                            return;
                        }

                        // 更新或创建水平线
                        if (CrossLevel == null)
                        {
                            CrossLevel = CreateLineSegment(
                                new MVD_POINT_F(0, nImagePointY),
                                new MVD_POINT_F(Image.Width, nImagePointY),
                                new MVD_COLOR(255, 255, 0, 255),
                                3,
                                MVD_DASH_STYLE.MvDashStyleDashDotDot
                            );
                        }
                        else
                        {
                            UpdateLineSegment(CrossLevel,
                                new MVD_POINT_F(0, nImagePointY),
                                new MVD_POINT_F(Image.Width, nImagePointY));
                        }

                        // 更新或创建垂直线
                        if (CrossVertical == null)
                        {
                            CrossVertical = CreateLineSegment(
                                new MVD_POINT_F(nImagePointX, 0),
                                new MVD_POINT_F(nImagePointX, Image.Height),
                                new MVD_COLOR(255, 255, 0, 255),
                                3,
                                MVD_DASH_STYLE.MvDashStyleDash
                            );

                        }
                        else
                        {
                            UpdateLineSegment(CrossVertical,
                                new MVD_POINT_F(nImagePointX, 0),
                                new MVD_POINT_F(nImagePointX, Image.Height));
                        }
                        TextContent.Interaction = false;
                        TextContent.BorderColor = new MVD_COLOR(255, 0, 0, 255);
                        TextContent.FontWidth = 15;
                        TextContent.Position = new MVDTextPosition(Image.Width, Image.Height, MVDTextPositionType.BottomRight);
                        TextContent.Content = $"十字中心坐标X:{nImagePointX},坐标Y:{nImagePointY}";
                        cMvdShape = TextContent;
                        AddShape(cMvdShape);
                        // ContentLabel1.Text = $"十字中心坐标X:{nImagePointX},坐标Y:{nImagePointY}";
                        AddShape(CrossLevel);
                        AddShape(CrossVertical);
                    }
                    MVDRender.Display();
                }
                if (CenterFlag)
                {
                    if (_ImageLoaded)
                    {

                        // 更新或创建水平线
                        if (CrossLevel1 == null)
                        {
                            CrossLevel1 = CreateLineSegment(
                                new MVD_POINT_F(0, Image.Height / 2),
                                new MVD_POINT_F(Image.Width, Image.Height / 2),
                                new MVD_COLOR(255, 255, 0, 255),
                                3,
                                MVD_DASH_STYLE.MvDashStyleDashDotDot
                            );
                        }
                        // 更新或创建垂直线
                        if (CrossVertical1 == null)
                        {
                            CrossVertical1 = CreateLineSegment(
                                new MVD_POINT_F(Image.Width / 2, 0),
                                new MVD_POINT_F(Image.Width / 2, Image.Height),
                                new MVD_COLOR(255, 255, 0, 255),
                                3,
                                MVD_DASH_STYLE.MvDashStyleDash
                            );

                        }
                        AddShape(CrossLevel1);
                        AddShape(CrossVertical1);
                    }
                    MVDRender.Display();
                }
            }
        }

        /// <summary>
        /// 触发事件
        /// </summary>
        /// <param name="enEventType"></param>
        /// <param name="enShapeType"></param>
        /// <param name="cShapeObj"></param>
        public void MVDRender_MVDShapeChangedEvent
            (
            MVDRenderActivex.MVD_SHAPE_EVENT_TYPE enEventType,
            MVD_SHAPE_TYPE enShapeType,
            CMvdShape cShapeObj
            )
        {

            try
            {
                if (MVDRenderActivex.MVD_SHAPE_EVENT_TYPE.MVD_SHAPE_SELECTED == enEventType)
                {
                    selectShape = cShapeObj;
                    return;
                }
                else if (MVDRenderActivex.MVD_SHAPE_EVENT_TYPE.MVD_SHAPE_EDITED == enEventType)
                {
                    if (enShapeType == MVD_SHAPE_TYPE.MvdShapePolylineSegment)
                    {
                        selectShape = cShapeObj;
                        // 获取点集
                        CMvdPolylineSegmentF? Polyline = cShapeObj as CMvdPolylineSegmentF;
                        if (Polyline != null)
                        {
                            List<(float X, float Y)> points = new List<(float X, float Y)>();
                            foreach (var item in Polyline.VertexList)
                            {
                                points.Add((item.fX, item.fY));
                            }

                            // 触发事件，将点集传递出去
                            TrajectoryPointsGenerated?.Invoke(this, new TrajectoryPointsEventArgs(points));
                        }
                    }
                    else if (enShapeType == MVD_SHAPE_TYPE.MvdShapeRectangle || enShapeType == MVD_SHAPE_TYPE.MvdShapeCircle)
                    {
                        m_ROI = cShapeObj;


                        if (Image.PixelFormat != MVD_PIXEL_FORMAT.MVD_PIXEL_MONO_08)
                        {
                            Image.ConvertImagePixelFormat(MVD_PIXEL_FORMAT.MVD_PIXEL_MONO_08);
                        }
                        ROIShapeCreated?.Invoke(this, new ROIShapeEventArgs(Image, cShapeObj));
                    }

                    return;

                }
                else if (MVDRenderActivex.MVD_SHAPE_EVENT_TYPE.MVD_SHAPE_ADDED == enEventType)
                {
                    selectShape = null;
                    if (enShapeType == MVD_SHAPE_TYPE.MvdShapePolylineSegment)
                    {
                        cShapeObj.BorderWidth = 5;
                        cShapeObj.Interaction = true;
                        MVDRender.UpdateShapeInfo(ref cShapeObj, true);
                        _addedShapes.Add(cShapeObj);
                        // 获取点集
                        CMvdPolylineSegmentF Polyline = cShapeObj as CMvdPolylineSegmentF;
                        if (Polyline != null)
                        {
                            List<(float X, float Y)> points = new List<(float X, float Y)>();
                            foreach (var item in Polyline.VertexList)
                            {
                                points.Add((item.fX, item.fY));
                            }

                            // 触发事件，将点集传递出去
                            TrajectoryPointsGenerated?.Invoke(this, new TrajectoryPointsEventArgs(points));
                        }
                    }
                    else if (enShapeType == MVD_SHAPE_TYPE.MvdShapeLineSegment)
                    {
                        selectShape = cShapeObj;
                        CMvdLineSegmentF? Polyline = cShapeObj as CMvdLineSegmentF;
                        _addedShapes.Add(Polyline);
                        if (Polyline != null)
                        {
                            System.Windows.MessageBox.Show($"距离为：{Math.Sqrt(Math.Pow(Polyline.StartPoint.fX - Polyline.EndPoint.fX, 2) + Math.Pow(Polyline.StartPoint.fY - Polyline.EndPoint.fY, 2))} ");
                            List<(float X, float Y)> points = new List<(float X, float Y)>();
                        }
                    }
                    else if (enShapeType == MVD_SHAPE_TYPE.MvdShapeRectangle || enShapeType == MVD_SHAPE_TYPE.MvdShapeCircle)
                    {
                        RemoveShape(m_ROI);
                        m_ROI = cShapeObj;
                        _addedShapes.Add(cShapeObj);
                        if (Image.PixelFormat != MVD_PIXEL_FORMAT.MVD_PIXEL_MONO_08)
                        {
                            Image.ConvertImagePixelFormat(MVD_PIXEL_FORMAT.MVD_PIXEL_MONO_08);
                        }
                        ROIShapeCreated?.Invoke(this, new ROIShapeEventArgs(Image, cShapeObj));
                    }
                }
            }
            catch (Exception e)
            {

            }
            finally
            {
                MVDRender.Display();
            }
        }
        #endregion
        #region 方法
        //public static void GetCircleFromThreePoints(MVD_POINT_F p1, MVD_POINT_F p2, MVD_POINT_F p3, out MVD_POINT_F center, out double radius)
        //{
        //    double x1 = p1.fX, y1 = p1.fY;
        //    double x2 = p2.fX, y2 = p2.fY;
        //    double x3 = p3.fX, y3 = p3.fY;

        //    // 计算三角形的边长
        //    double a = Math.Sqrt((x2 - x3) * (x2 - x3) + (y2 - y3) * (y2 - y3));  // P2-P3
        //    double b = Math.Sqrt((x1 - x3) * (x1 - x3) + (y1 - y3) * (y1 - y3));  // P1-P3
        //    double c = Math.Sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));  // P1-P2

        //    // 计算外接圆的 D 值
        //    double D = 2 * (x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2));
        //    if (Math.Abs(D) < 1e-10)  // 避免除 0 错误
        //    {
        //        center = new MVD_POINT_F(0, 0);
        //        radius = 0;
        //        return;
        //    }

        //    // 计算圆心坐标
        //    double cx = ((x1 * x1 + y1 * y1) * (y2 - y3) + (x2 * x2 + y2 * y2) * (y3 - y1) + (x3 * x3 + y3 * y3) * (y1 - y2)) / D;
        //    double cy = ((x1 * x1 + y1 * y1) * (x3 - x2) + (x2 * x2 + y2 * y2) * (x1 - x3) + (x3 * x3 + y3 * y3) * (x2 - x1)) / D;
        //    center = new MVD_POINT_F((float)cx, (float)cy);

        //    // 计算三角形面积
        //    double S = 0.5 * Math.Abs(x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2));

        //    // 计算外接圆半径
        //    radius = (a * b * c) / (4 * S);
        //}



        /// <summary>
        /// 计算圆弧参数，包括圆心、半径、起点角度、终点角度和方向
        /// </summary>
        //public static void GetArcParameters(MVD_POINT_F p1, MVD_POINT_F p2, MVD_POINT_F p3,
        //                                    out MVD_POINT_F center, out double radius,
        //                                    out double startAngle, out double endAngle,
        //                                    out double isCounterClockwise)
        //{
        //    double x1 = p1.fX, y1 = p1.fY;
        //    double x2 = p2.fX, y2 = p2.fY;
        //    double x3 = p3.fX, y3 = p3.fY;

        //    // 计算圆心和半径
        //    double D = 2 * (x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2));
        //    if (Math.Abs(D) < 1e-10)  // 避免除 0 错误
        //    {
        //        center = new MVD_POINT_F(0, 0);
        //        radius = 0;
        //        startAngle = endAngle = 0;
        //        isCounterClockwise = 0;
        //        return;
        //    }

        //    double cx = ((x1 * x1 + y1 * y1) * (y2 - y3) + (x2 * x2 + y2 * y2) * (y3 - y1) + (x3 * x3 + y3 * y3) * (y1 - y2)) / D;
        //    double cy = ((x1 * x1 + y1 * y1) * (x3 - x2) + (x2 * x2 + y2 * y2) * (x1 - x3) + (x3 * x3 + y3 * y3) * (x2 - x1)) / D;
        //    center = new MVD_POINT_F((float)cx, (float)cy);

        //    // 计算半径
        //    radius = Math.Sqrt((cx - x1) * (cx - x1) + (cy - y1) * (cy - y1));

        //    // 计算起点和终点的角度（弧度制）
        //    startAngle = Math.Atan2(y1 - cy, x1 - cx);
        //    endAngle = Math.Atan2(y3 - cy, x3 - cx);

        //    // 计算方向 (使用叉积判断)
        //    double cross = (x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1);
        //   // isCounterClockwise = cross > 0;

        //    // 转换为角度
        //    startAngle = startAngle * (180.0 / Math.PI);
        //    endAngle = endAngle * (180.0 / Math.PI);

        //    // 归一化角度范围 [0, 360]
        //    startAngle = NormalizeAngle(startAngle);
        //    endAngle = NormalizeAngle(endAngle);
        //    isCounterClockwise = endAngle - startAngle;
        //}

        //private static double NormalizeAngle(double angle)
        //{
        //    while (angle > 180) angle -= 360;
        //    while (angle <= -180) angle += 360;
        //    return angle;
        //}

        /// <summary>
        /// 去除之前的图形
        /// </summary>
        /// <param name="newShapes"></param>
        private void RemoveShapes(ObservableCollection<CMvdShape> oldShapes)
        {
            // 确保 MVDRender 已初始化
            if (MVDRender == null)
            {
                return;
            }

            if (oldShapes != null)
            {
                // 将新图形添加到 MVDRender
                foreach (var shape in oldShapes)
                {
                    RemoveShape(shape);
                }
            }
            // 更新显示
            MVDRender?.Display();
        }

        /// <summary>
        /// 更新图形集合
        /// </summary>
        /// <param name="newShapes"></param>
        private void UpdateShapes(ObservableCollection<CMvdShape> newShapes)
        {
            // 确保 MVDRender 已初始化
            if (MVDRender == null)
            {
                return;
            }

            if (newShapes != null)
            {
                // 将新图形添加到 MVDRender
                foreach (var shape in newShapes)
                {
                    AddShape(shape);
                }
            }
            // 更新显示
            MVDRender?.Display();
        }

        // 在某个逻辑中触发事件
        protected virtual void OnPointDataSent(double x, double y)
        {
            PointDataSent?.Invoke(this, new PointDataEventArgs(x, y));
        }

        private UInt32 itou<T>(T num)
        {
            return System.Convert.ToUInt32(num);
        }

        private Int32 utoi<T>(T num)
        {
            return System.Convert.ToInt32(num);
        }

        /// <summary>
        /// 添加图形
        /// </summary>
        /// <param name="shape"></param>
        public void AddShape(CMvdShape? shape)
        {
            if (shape == null)
            {
                return;
            }
            if (!_addedShapes.Contains(shape))
            {
                MVDRender.AddShape(shape);
                _addedShapes.Add(shape);
            }
            else
            {
                MVDRender.UpdateShapeInfo(ref shape, true);
            }
        }

        /// <summary>
        /// 删除图形
        /// </summary>
        /// <param name="shape"></param>
        public void RemoveShape(CMvdShape? shape)
        {
            if (shape == null)
            {
                return;
            }
            if (_addedShapes.Contains(shape))
            {
                MVDRender.DeleteShape(shape);
                _addedShapes.Remove(shape);
            }
        }

        /// <summary>
        /// 创建线段对象
        /// </summary>
        /// <param name="start">起点</param>
        /// <param name="end">终点</param>
        /// <param name="color">线条颜色</param>
        /// <param name="width">线条宽度</param>
        /// <param name="style">线条样式</param>
        /// <returns>CMvdLineSegmentF 对象</returns>

        private CMvdLineSegmentF CreateLineSegment(MVD_POINT_F start, MVD_POINT_F end, MVD_COLOR color, uint width, MVD_DASH_STYLE style)
        {

            CMvdLineSegmentF lineSegment = new CMvdLineSegmentF(start, end)
            {
                BorderColor = color,
                BorderWidth = width,
                BorderStyle = style
            };
            return lineSegment;
        }

        /// <summary>
        /// 更新线段对象的起点和终点
        /// </summary>
        /// <param name="lineSegment">需要更新的线段对象</param>
        /// <param name="start">新的起点</param>
        /// <param name="end">新的终点</param>
        private void UpdateLineSegment(CMvdLineSegmentF lineSegment, MVD_POINT_F start, MVD_POINT_F end)
        {
            lineSegment.StartPoint = start;
            lineSegment.EndPoint = end;
        }

        #endregion
        #region 绘制轨迹

        /// <summary>
        /// 开始绘图模式
        /// </summary>
        /// <param name="drawingState">要激活的绘图状态</param>
        public void StartDrawing(DrawingState drawingState)
        {
            // 设置绘图状态
            currentDrawingState = drawingState;

            // 重置绘图相关变量
            firstPoint = null;
            secondPoint = null;
            curvePoints.Clear();

            // 设置鼠标指针为十字形
            MVDRender.Cursor = Cursors.Cross;

            // 可选：显示用户提示
            string message = "";
            switch (drawingState)
            {
                case DrawingState.DrawingRectangle:
                    message = "请点击并拖动鼠标绘制矩形";
                    break;
                case DrawingState.DrawingLine:
                    message = "请点击起点，然后点击终点绘制线段";
                    break;
                case DrawingState.DrawingArc:
                    message = "请点击三个点以确定圆弧";
                    break;
                case DrawingState.DrawingInterpolatedCurve:
                    message = "请点击添加曲线控制点，右键结束绘制";
                    break;
                default:
                    message = "点击以开始绘制";
                    break;
            }

            // 显示提示信息
            ContentLabel.Text = message;
            ContentLabel.Refresh();

            // 开始预览更新
            previewUpdateTimer.Start();
        }


        /// <summary>
        /// 结束绘图模式
        /// </summary>
        public void EndDrawing()
        {
            currentDrawingState = DrawingState.None;
            firstPoint = null;
            secondPoint = null;
            curvePoints.Clear();

            // 停止预览更新并清除预览图形
            previewUpdateTimer.Stop();
            if (previewShape != null)
            {
                OverlayFrom.ClearPreview();
                previewShape = null;
            }


            MVDRender.Cursor = Cursors.Default;
            ContentLabel.Text = "";
            ContentLabel.Refresh();
        }

        #endregion  
        #region 图形绘制处理方法

        // 矩形绘制
        private void HandleRectangleDrawing(int imageX, int imageY, int overlayX, int overlayY)
        {
            if (!firstPoint.HasValue)
            {
                // 第一次点击，记录起始点
                firstPoint = new System.Drawing.Point(imageX, imageY);
                //ContentLabel.Text = "请拖动鼠标并释放以完成矩形";
            }
            else
            {
                // 第二次点击，完成矩形绘制
                int firstOverlayX, firstOverlayY;
                _displayControl.ImageToOverlay(firstPoint.Value.X, firstPoint.Value.Y, out firstOverlayX, out firstOverlayY);

                // 创建矩形，同时初始化Overlay坐标和图像坐标
                RectangleShape rect = new RectangleShape(
                    firstOverlayX, firstOverlayY,  // 左上角Overlay坐标
                    overlayX, overlayY,            // 右下角Overlay坐标
                    firstPoint.Value.X, firstPoint.Value.Y,  // 左上角图像坐标
                    imageX, imageY,                // 右下角图像坐标
                    new Pen(Color.Red, 2));

                // 检查矩形是否足够大
                if (rect.Width > 5 && rect.Height > 5) // 忽略太小的矩形
                {
                    OverlayFrom.AddShape(rect);

                    // 触发绘制完成事件
                    OnShapeDrawn(rect, ShapeType.Rectangle,
                        rect.GetImageCoordinatePoints(),
                        rect.GetOverlayCoordinatePoints());
                }

                // 结束绘制
                EndDrawing();
            }
        }

        // 线段绘制
        private void HandleLineDrawing(int imageX, int imageY, int overlayX, int overlayY)
        {
            if (!firstPoint.HasValue)
            {
                // 第一次点击，记录起始点
                firstPoint = new System.Drawing.Point(imageX, imageY);
                //ContentLabel.Text = "请点击第二个点以完成线段";
            }
            else
            {
                // 第二次点击，完成线段绘制
                int firstOverlayX, firstOverlayY;
                _displayControl.ImageToOverlay(firstPoint.Value.X, firstPoint.Value.Y, out firstOverlayX, out firstOverlayY);

                PointF startPoint = new PointF(firstOverlayX, firstOverlayY);
                PointF endPoint = new PointF(overlayX, overlayY);

                // 创建图像坐标点
                PointF startPointImage = new PointF(firstPoint.Value.X, firstPoint.Value.Y);
                PointF endPointImage = new PointF(imageX, imageY);

                // 线段长度检查
                float length = (float)Math.Sqrt(
                    Math.Pow(endPoint.X - startPoint.X, 2) +
                    Math.Pow(endPoint.Y - startPoint.Y, 2));

                if (length > 5) // 忽略太短的线段
                {
                    // 创建线段时同时初始化Overlay坐标和图像坐标
                    LineShape line = new LineShape(startPoint, endPoint, startPointImage, endPointImage);
                    OverlayFrom.AddShape(line);

                    // 触发绘制完成事件
                    OnShapeDrawn(line, ShapeType.Line,
                        line.GetImageCoordinatePoints(),
                        line.GetOverlayCoordinatePoints());
                }

                // 结束绘制
                EndDrawing();
            }
        }

        // 圆弧绘制
        private void HandleArcDrawing(int imageX, int imageY, int overlayX, int overlayY)
        {
            if (!firstPoint.HasValue)
            {
                // 第一次点击，记录第一个点
                firstPoint = new System.Drawing.Point(imageX, imageY);
                //ContentLabel.Text = "请点击第二个点";
            }
            else if (!secondPoint.HasValue)
            {
                // 第二次点击，记录第二个点
                secondPoint = new System.Drawing.Point(imageX, imageY);
                //ContentLabel.Text = "请点击第三个点以完成圆弧";
            }
            else
            {
                // 第三次点击，完成圆弧绘制
                int firstOverlayX, firstOverlayY;
                _displayControl.ImageToOverlay(firstPoint.Value.X, firstPoint.Value.Y, out firstOverlayX, out firstOverlayY);

                int secondOverlayX, secondOverlayY;
                _displayControl.ImageToOverlay(secondPoint.Value.X, secondPoint.Value.Y, out secondOverlayX, out secondOverlayY);

                PointF point1 = new PointF(firstOverlayX, firstOverlayY);
                PointF point2 = new PointF(secondOverlayX, secondOverlayY);
                PointF point3 = new PointF(overlayX, overlayY);

                // 创建图像坐标点
                PointF point1Image = new PointF(firstPoint.Value.X, firstPoint.Value.Y);
                PointF point2Image = new PointF(secondPoint.Value.X, secondPoint.Value.Y);
                PointF point3Image = new PointF(imageX, imageY);

                try
                {
                    // 创建圆弧时同时初始化Overlay坐标和图像坐标
                    ArcShape arc = new ArcShape(point1, point2, point3, point1Image, point2Image, point3Image);
                    OverlayFrom.AddShape(arc);

                    OnShapeDrawn(arc, ShapeType.Arc,
                        arc.GetImageCoordinatePoints(),
                        arc.GetOverlayCoordinatePoints());
                }
                catch (ArgumentException)
                {
                    // 无法创建有效圆弧，回退到创建线段
                    LineShape line = new LineShape(point1, point3, point1Image, point3Image);
                    OverlayFrom.AddShape(line);
                    //ContentLabel.Text = "无法创建圆弧：点位共线，已创建线段";

                    OnShapeDrawn(line, ShapeType.Line, line.GetImageCoordinatePoints(), line.GetOverlayCoordinatePoints());
                }

                // 结束绘制
                EndDrawing();
            }
        }

        // 处理曲线绘制
        private void HandleCurveDrawing(int imageX, int imageY, int overlayX, int overlayY)
        {
            // 添加一个新点，存储图像坐标而非窗口坐标
            curvePoints.Add(new System.Drawing.Point(imageX, imageY));
            //ContentLabel.Text = $"已添加 {curvePoints.Count} 个点，左键继续添加，右键完成绘制";

            // 立即更新预览，传递图像坐标
            UpdateCurvePreview(imageX, imageY);
        }

        // 完成曲线绘制
        private void FinalizeCurveDrawing()
        {
            if (curvePoints.Count < 2)
            {
                //ContentLabel.Text = "需要至少2个点才能创建曲线";
                return;
            }

            try
            {
                // 创建图像坐标点数组
                List<PointF> imagePoints = new List<PointF>();
                foreach (var point in curvePoints)
                {
                    imagePoints.Add(new PointF(point.X, point.Y));
                }

                // 转换点集，从图像坐标到overlay坐标
                List<PointF> overlayPoints = new List<PointF>();
                foreach (var point in curvePoints)
                {
                    int pointX, pointY;
                    // 从图像坐标转换为Overlay坐标
                    _displayControl.ImageToOverlay(point.X, point.Y, out pointX, out pointY);
                    overlayPoints.Add(new PointF(pointX, pointY));
                }

                // 创建最终曲线
                Pen finalPen = new Pen(Color.Red, 2);
                InterpolatedCurveShape curve = new InterpolatedCurveShape(overlayPoints, imagePoints, finalPen);

                OverlayFrom.AddShape(curve);
                //ContentLabel.Text = "曲线已创建! 共 " + curvePoints.Count + " 个控制点";

                // 触发事件
                OnShapeDrawn(curve, ShapeType.InterpolatedCurve,
                            curve.GetImageCoordinatePoints(),
                            curve.GetOverlayCoordinatePoints());
            }
            catch (Exception ex)
            {
                //ContentLabel.Text = "创建曲线失败: " + ex.Message;
            }

            // 结束绘制
            EndDrawing();
        }


        #endregion
        #region 预览更新事件

        // 预览更新定时器事件处理
        private void PreviewUpdateTimer_Tick(object sender, EventArgs e)
        {
            if (previewShape != null)
            {
                // 更新图层显示
                OverlayFrom.UpdatePreview(previewShape);
            }
        }

        // 矩形预览
        private void UpdateRectanglePreview(int imageX, int imageY)
        {
            if (!firstPoint.HasValue) return;

            // 转换第一个点和当前点到 overlay 坐标
            int firstOverlayX, firstOverlayY;
            _displayControl.ImageToOverlay(firstPoint.Value.X, firstPoint.Value.Y, out firstOverlayX, out firstOverlayY);

            int currentOverlayX, currentOverlayY;
            _displayControl.ImageToOverlay(imageX, imageY, out currentOverlayX, out currentOverlayY);

            // 创建或更新预览矩形
            if (previewShape == null || !(previewShape is RectangleShape))
            {
                previewShape = new RectangleShape(
                    firstOverlayX,
                    firstOverlayY,
                    currentOverlayX,
                    currentOverlayY);
            }
            else
            {
                RectangleShape rectShape = (RectangleShape)previewShape;
                rectShape.TopLeftX = firstOverlayX;
                rectShape.TopLeftY = firstOverlayY;
                rectShape.BottomRightX = currentOverlayX;
                rectShape.BottomRightY = currentOverlayY;
            }
        }

        // 圆弧预览
        private void UpdateArcPreview(int imageX, int imageY)
        {
            if (!firstPoint.HasValue || !secondPoint.HasValue) return;

            // 转换三个点到 overlay 坐标
            int firstOverlayX, firstOverlayY;
            _displayControl.ImageToOverlay(firstPoint.Value.X, firstPoint.Value.Y, out firstOverlayX, out firstOverlayY);

            int secondOverlayX, secondOverlayY;
            _displayControl.ImageToOverlay(secondPoint.Value.X, secondPoint.Value.Y, out secondOverlayX, out secondOverlayY);

            int currentOverlayX, currentOverlayY;
            _displayControl.ImageToOverlay(imageX, imageY, out currentOverlayX, out currentOverlayY);

            PointF point1 = new PointF(firstOverlayX, firstOverlayY);
            PointF point2 = new PointF(secondOverlayX, secondOverlayY);
            PointF point3 = new PointF(currentOverlayX, currentOverlayY);

            try
            {
                // 尝试创建预览圆弧
                previewShape = new ArcShape(point1, point2, point3);
            }
            catch (ArgumentException)
            {
                // 无法创建有效圆弧时，显示一个临时线段作为预览
                if (previewShape == null || !(previewShape is LineShape))
                {
                    previewShape = new LineShape(point1, point3);
                }
                else
                {
                    LineShape lineShape = (LineShape)previewShape;
                    lineShape.StartPoint = point1;
                    lineShape.EndPoint = point3;
                }
            }
        }

        // 线段预览更新
        private void UpdateLinePreview(int imageX, int imageY)
        {
            if (!firstPoint.HasValue) return;

            // 转换第一个点和当前点到 overlay 坐标
            int firstOverlayX, firstOverlayY;
            _displayControl.ImageToOverlay(firstPoint.Value.X, firstPoint.Value.Y, out firstOverlayX, out firstOverlayY);

            int currentOverlayX, currentOverlayY;
            _displayControl.ImageToOverlay(imageX, imageY, out currentOverlayX, out currentOverlayY);

            // 创建或更新预览线段
            if (previewShape == null || !(previewShape is LineShape))
            {
                previewShape = new LineShape(
                    new PointF(firstOverlayX, firstOverlayY),
                    new PointF(currentOverlayX, currentOverlayY));
            }
            else
            {
                LineShape lineShape = (LineShape)previewShape;
                lineShape.StartPoint = new PointF(firstOverlayX, firstOverlayY);
                lineShape.EndPoint = new PointF(currentOverlayX, currentOverlayY);
            }
        }

        // 曲线预览
        private void UpdateCurvePreview(int imageX, int imageY, int overlayX = 0, int overlayY = 0)
        {
            try
            {
                // 创建包含所有已点击点和当前鼠标位置的控制点列表
                List<PointF> overlayPoints = new List<PointF>();

                // 转换已存储的所有点到overlay坐标（curvePoints存储的是图像坐标）
                foreach (var point in curvePoints)
                {
                    int pointOverlayX, pointOverlayY;
                    // 从图像坐标转换为Overlay坐标
                    _displayControl.ImageToOverlay(point.X, point.Y, out pointOverlayX, out pointOverlayY);
                    overlayPoints.Add(new PointF(pointOverlayX, pointOverlayY));
                }

                // 添加当前鼠标位置作为临时点（使用提供的overlay坐标或转换图像坐标）
                if (curvePoints.Count > 0)
                {
                    if (overlayX != 0 || overlayY != 0)
                    {
                        overlayPoints.Add(new PointF(overlayX, overlayY));
                    }
                    else
                    {
                        int currentOverlayX, currentOverlayY;
                        // 从图像坐标转换为Overlay坐标
                        _displayControl.ImageToOverlay(imageX, imageY, out currentOverlayX, out currentOverlayY);
                        overlayPoints.Add(new PointF(currentOverlayX, currentOverlayY));
                    }
                }

                // 至少需要2个点才能创建曲线
                if (overlayPoints.Count >= 2)
                {
                    // 创建或更新预览曲线
                    if (previewShape == null || !(previewShape is InterpolatedCurveShape))
                    {
                        previewShape = new InterpolatedCurveShape(overlayPoints); // 添加虚线样式以区分预览
                    }
                    else
                    {
                        // 如果已经存在预览曲线，则更新其点集合
                        ((InterpolatedCurveShape)previewShape).UpdateControlPoints(overlayPoints);
                    }

                    // 更新预览
                    OverlayFrom.UpdatePreview(previewShape);
                }
            }
            catch (Exception ex)
            {
                // 记录错误但不中断用户操作
                Console.WriteLine("曲线预览错误: " + ex.Message);
                ContentLabel.Text = "曲线预览错误: " + ex.Message;
            }
        }

        #endregion
        #region 图形数据事件回调机制

        /// <summary>
        /// 图形绘制完成事件的参数类
        /// </summary>
        public class ShapeDrawnEventArgs : EventArgs
        {
            public ImageRenderControl.Shape DrawnShape { get; private set; }
            public ShapeType ShapeType { get; private set; }
            public PointF[] ImageCoordinates { get; private set; }
            public PointF[] OverlayCoordinates { get; private set; }

            public ShapeDrawnEventArgs(ImageRenderControl.Shape shape, ShapeType type, PointF[] imageCoords, PointF[] overlayCoords)
            {
                DrawnShape = shape;
                ShapeType = type;
                ImageCoordinates = imageCoords;
                OverlayCoordinates = overlayCoords;
            }
        }

        /// <summary>
        /// 在类的开头声明事件
        /// </summary>
        public event EventHandler<ShapeDrawnEventArgs> ShapeDrawn;

        /// <summary>
        /// 触发图形绘制完成事件的方法
        /// </summary>
        private void OnShapeDrawn(ImageRenderControl.Shape shape, ShapeType type, PointF[] imageCoords, PointF[] overlayCoords)
        {
            ShapeDrawn?.Invoke(this, new ShapeDrawnEventArgs(shape, type, imageCoords, overlayCoords));
        }


        #endregion 

    }

    public class PointDataEventArgs : EventArgs
    {
        public double X { get; set; }
        public double Y { get; set; }

        public PointDataEventArgs(double x, double y)
        {
            X = x;
            Y = y;
        }
    }

    public class TrajectoryPointsEventArgs : EventArgs
    {
        public List<(float X, float Y)> Points { get; }

        public TrajectoryPointsEventArgs(List<(float X, float Y)> points)
        {
            Points = points;
        }
    }

    public class ROIShapeEventArgs : EventArgs
    {
        public CMvdImage InputImage { get; set; }
        public CMvdShape ROI { get; set; }

        public ROIShapeEventArgs(CMvdImage input, CMvdShape roi)
        {
            InputImage = input;
            ROI = roi;
        }
    }

}
